package com.smart.dao;

import com.smart.domain.Lesson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository // 通过spring注解定义一个Dao
public class LessonClass {
    private JdbcTemplate jdbcTemplate;

    @Autowired // 自动注入jdbcTemplate 的bean
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    //插入
    public int addlesson(Lesson lesson) {

        final String sql = "insert into lesson(Lesson_name, Lesson_starTtime, Lesson_endTime, Lesson_NickName) VALUES(?,?,?,?)";
        Object[] params = new Object[]{lesson.getLesson_name(), lesson.getLesson_starTtime(), lesson.getLesson_endTime(), lesson.getLesson_NickName()};
        return jdbcTemplate.update(sql, params);
    }

    /**修改
     */
    public int updatelesson(Lesson lesson1) {
        final String sqlt = "update lesson set Lesson_name=?,Lesson_starTtime=?,Lesson_endTime where Lesson_NickName=?";
        return jdbcTemplate.update(sqlt, lesson1.getLesson_name(), lesson1.getLesson_starTtime(), lesson1.getLesson_endTime(), lesson1.getLesson_NickName());
    }

    /**
     * 删除
     */
    public int deletelesson(Lesson lesson1) {
        final String sql = "delete from lesson where Lesson_NickName=?";
        return jdbcTemplate.update(sql, lesson1.getLesson_NickName());
    }

    /**
     * 查询单个对象
     */
    public void Chaxun(Lesson lesson) {
        String sql = "select * from lesson where Lesson_NickName=?";
        Lesson les= jdbcTemplate.queryForObject(sql, new Lessonmy(), lesson.getLesson_NickName());
        System.out.println(les);
    }
    /**
     * 查询集合对象
     * @ return
     */
    public Lesson Chuxunquanbu(){
        String sql ="select * from lessson";
        List<Lesson> les=jdbcTemplate.query(sql,new Lessonmy());
        System.out.println(les);
        return null;
    }

}
class  Lessonmy implements RowMapper<Lesson>{
    @Override
    public Lesson mapRow(ResultSet rq, int i) throws SQLException {
        //1 从结果集里得到数据
        String  name =rq.getString("Lesson_name");
        Date starttime = rq.getDate("Lesson_starTtime");
        Date endtime =rq.getDate("Lesson_endTime");
        String  nickname=rq.getString("Lesson_NickName");
        //2 把得到数据封装到数据里面去
        Lesson les =new Lesson();
        les.setLesson_name(name);
        les.setLesson_starTtime(starttime);
        les.setLesson_endTime(endtime);
        les.setLesson_NickName(nickname);
        return les;
    }
}


